import { createContext, useContext, useState, useEffect } from 'react';
import { wxAuthConfig } from '../config';
import api from '../utils/api'; // Import the API service
import { useLocation } from 'react-router-dom';

const AuthContext = createContext();

export const AuthProvider = ({ children }) => {
  // 初始化时从localStorage获取用户信息
  const [user, setUser] = useState(() => {
    const savedUser = localStorage.getItem('user');
    return savedUser ? JSON.parse(savedUser) : null;
  });
  
  // 添加加载状态，防止在验证用户状态时出现闪烁或循环
  const [loading, setLoading] = useState(true);

  // 在组件挂载时验证用户状态
  useEffect(() => {
    const verifyUser = async () => {
      try {
        const savedUser = localStorage.getItem('user');
        if (savedUser) {
          // 如果localStorage中有用户信息，设置用户状态
          setUser(JSON.parse(savedUser));
        }
      } catch (error) {
        console.error('验证用户状态失败:', error);
        // 如果验证失败，清除用户状态
        logout();
      } finally {
        setLoading(false);
      }
    };

    verifyUser();
  }, []);

  const login = (userData) => {
    setUser(userData);
    localStorage.setItem('user', JSON.stringify(userData));
    // 设置默认Authorization header已在api.js中处理
  };

  const logout = () => {
    setUser(null);
    localStorage.removeItem('user');
    // 清除Authorization header已在api.js中处理
  };

  return (
    <AuthContext.Provider value={{ user, login, logout, loading }}>
      {children}
    </AuthContext.Provider>
  );
};

export const useAuth = () => {
  return useContext(AuthContext);
};
